<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="日期" prop="date">
        <el-date-picker clearable
                        v-model="queryParams.date"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="车次:" prop="trainCode">
        <el-input
          v-model="queryParams.trainCode"
          placeholder="请选择车次"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查找</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 双层折叠面板：第一层按车次分组 -->
    <el-collapse v-loading="loading" accordion>
      <el-collapse-item v-for="(trainGroup, trainIndex) in groupedSeats" :key="trainIndex" :name="trainIndex">
        <template slot="title">
          <div class="train-group-title">
            <span class="train-code">车次: {{ trainGroup.trainCode }}</span>
            <span class="seat-count">
              (共{{ getTotalSeatsCount(trainGroup) }}个座位)
            </span>
          </div>
        </template>

        <!-- 第二层按车厢分组 -->
        <el-collapse accordion>
          <el-collapse-item v-for="(carriageGroup, carriageIndex) in trainGroup.carriages" :key="carriageIndex" :name="carriageIndex">
            <template slot="title">
              <div class="carriage-group-title">
                <span class="carriage-index">车厢: {{ carriageGroup.carriageIndex }}</span>
                <span class="seat-type">
                  {{ getSeatTypeName(carriageGroup.seatType) }}
                  (共{{ carriageGroup.seats.length }}个座位)
                </span>
              </div>
            </template>

            <!-- 显示具体座位的表格 -->
            <el-table
              :data="carriageGroup.seats"
              border
              :row-style="{ height: '50px' }"
              @selection-change="handleSelectionChange"
              :default-sort="{prop: 'row', order: 'ascending'}"
              size="medium"
            >
<!--              <el-table-column show-overflow-tooltip type="selection" width="40" align="center" />-->
              <el-table-column show-overflow-tooltip label="ID" align="center" prop="id" />
              <el-table-column show-overflow-tooltip label="日期" align="center" prop="date"/>
              <el-table-column show-overflow-tooltip label="排号" align="center" prop="row"  sortable />
              <el-table-column show-overflow-tooltip label="列号" align="center" prop="col"  sortable />
              <el-table-column show-overflow-tooltip label="座位类型" align="center" >
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.seat_type" :value="scope.row.seatType"/>
                </template>
              </el-table-column>
              <el-table-column show-overflow-tooltip label="同车箱座序" align="center" prop="carriageSeatIndex"  />
              <el-table-column show-overflow-tooltip label="售卖情况" align="center" >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="primary"
                    plain
                    @click="showSellDetail(scope.row)"
                  >查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </el-collapse>
      </el-collapse-item>
    </el-collapse>

    <!-- 分页组件 - 修改为基于列车数量分页 -->
    <pagination
      v-show="trainTotal>0"
      :total="trainTotal"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改每日座位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 座位售卖情况详情弹窗 -->
    <el-dialog title="座位售卖详情" :visible.sync="sellDetailVisible" width="600px" append-to-body>
      <div v-if="currentSeat">
        <el-descriptions border :column="1">
          <el-descriptions-item label="车厢号">{{ currentSeat.carriageIndex }}</el-descriptions-item>
          <el-descriptions-item label="座位号">{{ currentSeat.row }}排{{ currentSeat.col }}列</el-descriptions-item>
          <el-descriptions-item label="座位类型">
            <dict-tag :options="dict.type.seat_type" :value="currentSeat.seatType"/>
          </el-descriptions-item>
        </el-descriptions>

        <div class="sell-segments-title">分段售卖情况：</div>
        <el-table
          :data="sellSegments"
          border
          size="small"
          style="margin-top: 10px"
          v-loading="sellSegmentsLoading"
        >
          <el-table-column label="站间区段" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.startStation }} → {{ scope.row.endStation }}</span>
            </template>
          </el-table-column>
          <el-table-column label="售卖状态" align="center" width="120">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === '1' ? 'danger' : 'success'">
                {{ scope.row.status === '1' ? '已售' : '可售' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDailyTrainSeat, getDailyTrainSeat, delDailyTrainSeat, addDailyTrainSeat, updateDailyTrainSeat } from "@/api/business/daily-train-seat";
import { listDailyTrainSeatByTrainGroup } from "@/api/business/daily-train-seat";
import { getSeatSellDetail } from "@/api/business/daily-train-seat";

export default {
  name: "Daily-train-seat",
  dicts: ['seat_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数 - 保留原有变量，但不再使用
      total: 0,
      // 列车总数 - 新增变量，用于分页显示
      trainTotal: 0,
      // 每日座位分组数据
      groupedSeats: [],
      // 每日座位表格数据 - 保留但不使用
      dailyTrainSeatList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        date: null,
        trainCode: null,
        paginationType: 'train' // 新增参数，表明按列车分页
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 座位售卖情况详情弹窗
      sellDetailVisible: false,
      // 当前选中的座位
      currentSeat: null,
      // 售卖区段数据
      sellSegments: [],
      // 售卖区段加载状态
      sellSegmentsLoading: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询每日座位列表（按车次分组，并按车次分页） */
    getList() {
      this.loading = true;
      listDailyTrainSeatByTrainGroup(this.queryParams).then(response => {
        this.groupedSeats = response.rows;
        this.trainTotal = response.total; // 使用trainTotal存储列车总数
        this.loading = false;
      });
    },

    // 获取指定车次的总座位数
    getTotalSeatsCount(trainGroup) {
      let total = 0;
      if (trainGroup && trainGroup.carriages) {
        trainGroup.carriages.forEach(carriage => {
          total += carriage.seats ? carriage.seats.length : 0;
        });
      }
      return total;
    },

    // 获取座位类型名称
    getSeatTypeName(type) {
      const seatTypes = this.dict.type.seat_type;
      if (seatTypes) {
        const found = seatTypes.find(item => item.value === type);
        if (found) {
          return found.label;
        }
      }
      return type;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        date: null,
        trainCode: null,
        carriageIndex: null,
        row: null,
        col: null,
        seatType: null,
        carriageSeatIndex: null,
        sell: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加每日座位";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDailyTrainSeat(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改每日座位";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDailyTrainSeat(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDailyTrainSeat(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除每日座位编号为"' + ids + '"的数据项？').then(function() {
        return delDailyTrainSeat(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/daily-train-seat/export', {
        ...this.queryParams
      }, `daily-train-seat_${new Date().getTime()}.xlsx`)
    },
    // 显示座位售卖情况详情
    showSellDetail(seat) {
      this.currentSeat = seat;
      this.sellDetailVisible = true;
      this.loadSellSegments(seat);
    },
    // 加载座位售卖区段信息
    loadSellSegments(seat) {
      this.sellSegmentsLoading = true;
      this.sellSegments = [];

      // 调用后端API获取座位售卖详情
      getSeatSellDetail({
        date: seat.date,
        trainCode: seat.trainCode,
        seatId: seat.id
      }).then(response => {
        this.sellSegments = response.data || [];
        this.sellSegmentsLoading = false;
      }).catch(() => {
        this.sellSegmentsLoading = false;
        this.$message.error('获取座位售卖详情失败');
      });
    },
    // 获取座位售卖状态类型
    getSellStatusType(sell) {
      if (sell === '1') {
        return 'danger';
      } else if (sell === '0') {
        return 'success';
      } else {
        return '';
      }
    }
  }
};
</script>

<style>
/* 折叠面板相关样式 */
.train-group-title {
  display: flex;
  align-items: center;
  font-size: 15px;
}

.train-code {
  font-weight: bold;
  margin-right: 20px;
  min-width: 100px;
}

.seat-count {
  color: #606266;
  font-size: 13px;
}

.carriage-group-title {
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-left: 10px;
}

.carriage-index {
  font-weight: bold;
  margin-right: 20px;
  min-width: 80px;
}

.seat-type {
  color: #606266;
}

/* 增加嵌套折叠面板的视觉区分 */
.el-collapse-item__header {
  height: 60px;
  line-height: 60px;
  background-color: #f5f7fa;
  padding-left: 15px;
}

.el-collapse .el-collapse {
  margin-left: 20px;
}

.el-collapse .el-collapse .el-collapse-item__header {
  background-color: #eaedf1;
  height: 50px;
  line-height: 50px;
}

.el-collapse-item__content {
  padding: 10px;
}

/* 售卖情况详情样式 */
.sell-segments-title {
  margin: 15px 0 5px 0;
  font-weight: bold;
  color: #303133;
}
</style>
